package com.atguigu.admin.controller;

import com.atguigu.admin.param.AdminUserParam;
import com.atguigu.admin.service.AdminUserService;
import com.atguigu.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.admin.pojo.AdminUser;
import javax.servlet.http.HttpSession;

/**
 * ClassName:AdminUserController
 * Package:com.atguigu.admin.controller
 * Description:
 *
 * @Author 应永豪
 * @Create 2024/4/23 10:24
 * @Version 1.0
 */
@RestController
public class AdminUserController {
    @Autowired
    private AdminUserService adminUserService;

    @PostMapping("/user/login")
    public R login(@Validated AdminUserParam adminUserParam, BindingResult bindingResult, HttpSession httpSession){
        if (bindingResult.hasErrors()){
            return R.fail("核心参数为null，登录失败");
        }

        String captcha = (String) httpSession.getAttribute("captcha");

        if (!adminUserParam.getVerCode().equalsIgnoreCase(captcha)){
            return R.fail("验证码错误");
        }
        AdminUser user = adminUserService.login(adminUserParam);

        if (user==null){
            return R.fail("登录失败。账号或者密码错误");
        }

        httpSession.setAttribute("userInfo",user);
        return R.ok("登录成功");

    }

    @GetMapping("/user/logout")
    public R logout(HttpSession httpSession){
//        清空sessin
        httpSession.invalidate();
        return R.ok("退出登录成功");
    }
}
